package com.example.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.common.lang.Result;
import com.example.entity.Diary;
import com.example.service.DiaryService;
import com.example.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cyk
 * @since 2022-04-30
 */
@RestController
public class DiaryController {

    @Autowired
    DiaryService diaryService;

    /**
     * 查询用户的全部日记信息，分页显示
     * @param currentPage
     * @return
     */
    @ResponseBody
    @GetMapping("/diaryAll/{stuId}")
    public Result diaryAll(@PathVariable(name = "stuId") Long stuId,
                           @RequestParam(defaultValue = "1") Integer currentPage){

        PageUtils page = new PageUtils();
        List<Diary> list = diaryService.diaryAll(stuId);
        IPage pageData = page.getDiaryPage(currentPage,5,list);

        return Result.succ(pageData);
    }

    /**
     * 根据id查询用户的日记信息
     * @return
     */
    @ResponseBody
    @GetMapping("/diaryById/{id}")
    public Result diaryById(@PathVariable(name = "id") Long id){

        Diary list = diaryService.diaryById(id);

        return Result.succ(list);
    }

    /**
     * 根据id删除用户的日记信息
     * @return
     */
    @ResponseBody
    @GetMapping("/delDiary/{id}")
    public Result delDiary(@PathVariable(name = "id") Long id){

        int i = diaryService.delDiary(id);

        if (i > 0){
            return Result.succ(200,"删除成功！",null);
        } else {
            return Result.succ(200,"删除失败！",null);
        }
    }

    /**
     * 编辑
     * @param diary
     * @return
     */
    @PostMapping("/diaryEdit")
    public Result diaryEdit(@Validated @RequestBody Diary diary){

        LocalDateTime date = diary.getDate();
        Diary temp = new Diary();
        temp.setId(diary.getId());
        temp.setCompany(diary.getCompany());
        temp.setPost(diary.getPost());
        temp.setStatus(diary.getStatus());
        temp.setDate(diary.getDate());
        temp.setRemarks(diary.getRemarks());
        temp.setStuId(diary.getStuId());

        if (temp.getId() != null){
            // 修改
            int i = diaryService.updateDiary(temp);
            if (i > 0){
                return Result.succ(200,"修改成功！",null);
            } else {
                return Result.succ(200,"修改失败！",null);
            }
        } else {
            // 添加
            int i = diaryService.saveDiary(temp);
            if (i > 0){
                return Result.succ(200,"添加成功！",null);
            } else {
                return Result.succ(200,"添加失败！",null);
            }
        }
    }

}
